from PyQt5.QtGui import Qt,QPixmap,QColor,QPainter,QFont,QPalette
from PyQt5.QtCore import pyqtSignal,QPointF
from PyQt5.QtWidgets import QWidget,QLabel,QMenu,QApplication,QVBoxLayout,\
    QHBoxLayout,QPushButton,QGridLayout,QFileDialog,QMessageBox,QRadioButton
from  mylibs.ImgZengQiang import imageProcessor
from  mylibs.mouseRect import drawRect
import os

FONTSTR = 'Arial'
APPFONT = QFont(FONTSTR)
FONT_SIZE1 = 15
FONT_SIZE2 = 12
FONT_SIZE3 = 10

class angleMessurement(QWidget):
    def __init__(self,labelImgdir,parent=None):
        super(angleMessurement, self).__init__(parent)
        self.imageZQList = []
        self.drawRect = None
        self.enhanceImgdir = labelImgdir
        # self.resize(600, 600)
        self.setWindowTitle('Images Editor')
        # self.setStyleSheet("background: black")
        self.layout = QVBoxLayout()
        ImgZQhlyout = QHBoxLayout()
        ImgZQWid = QWidget(self)
        ImgZQLabel = QLabel('Image Enhencing')
        ImgZQLabel.setFont(QFont(FONTSTR,FONT_SIZE1))
        ImgZQhlyout.addWidget(ImgZQLabel)
        ImgZQStartbtn = QPushButton('Start')
        ImgZQStartbtn.clicked.connect(self.startImgZQ)
        ImgZQStartbtn.setFont(QFont(FONTSTR,FONT_SIZE2))
        ImgZQhlyout.addStretch()
        ImgZQhlyout.addWidget(ImgZQStartbtn)
        ImgZQWid.setLayout(ImgZQhlyout)
        self.layout.addWidget(ImgZQWid)
        gridW = QWidget()
        gridlayout = QGridLayout()
        gridW.setLayout(gridlayout)
        positions = [(i,j) for i in range(3) for j in range(4)]
        names = ['vertical_flip', 'horizon_flip', 'rotation',
                 'translate', 'deform', 'scretch', 'hue',
                 'bright', 'crop', 'saturation']
        self.labelNumDic = {}
        for position,name in zip(positions,names):
            w,btn1,btn2,labelNum = self.createImgZQLabel(name)
            gridlayout.addWidget(w,*position)
            if labelNum.objectName() == names[0]:
                self.labelNumDic['0']= labelNum
                btnvf1,btnvf2 = self.getLabelNumbtn(name,btn1,btn2)
            elif labelNum.objectName() == names[1]:
                self.labelNumDic['1'] = labelNum
                btnht1, btnhf2 = self.getLabelNumbtn(name, btn1, btn2)
            elif labelNum.objectName() == names[2]:
                self.labelNumDic['2'] = labelNum
                btnrt1, btnrt2 = self.getLabelNumbtn(name, btn1, btn2)
            elif labelNum.objectName() == names[3]:
                self.labelNumDic['3'] = labelNum
                btntr1, btntr2 = self.getLabelNumbtn(name, btn1, btn2)
            elif labelNum.objectName() == names[4]:
                self.labelNumDic['4'] = labelNum
                btnde1, btnde2 = self.getLabelNumbtn(name, btn1, btn2)
            elif labelNum.objectName() == names[5]:
                self.labelNumDic['5'] = labelNum
                btnsc1, btnsc2 = self.getLabelNumbtn(name, btn1, btn2)
            elif labelNum.objectName() == names[6]:
                self.labelNumDic['6'] = labelNum
                btnhu1, btnhu2 = self.getLabelNumbtn(name, btn1, btn2)
            elif labelNum.objectName() == names[7]:
                self.labelNumDic['7'] = labelNum
                btnbr1, btnbr2 = self.getLabelNumbtn(name, btn1, btn2)
            elif labelNum.objectName() == names[8]:
                self.labelNumDic['8'] = labelNum
                btncr1, btncr2 = self.getLabelNumbtn(name, btn1, btn2)
            elif labelNum.objectName() == names[9]:
                self.labelNumDic['9'] = labelNum
                btnsa1, btnsa2 = self.getLabelNumbtn(name, btn1, btn2)
        self.layout.addWidget(gridW)
        self.setLayout(self.layout)

        angleLabel = QLabel('Deflection angle measurement & Correction')
        angleLabel.setFont(QFont(FONTSTR, FONT_SIZE1))
        self.layout.addWidget(angleLabel)
        radiobtn1 = QRadioButton('Create Template')
        # radiobtn1.setChecked(True)
        radiobtn2 = QRadioButton("Load Template")
        self.radiobtn3 = QRadioButton("Angle Messurement and Image Correction")
        self.radiobtn3.setEnabled(False)
        radiobtn1.setFont(QFont(FONTSTR, FONT_SIZE2))
        radiobtn2.setFont(QFont(FONTSTR, FONT_SIZE2))
        self.radiobtn3.setFont(QFont(FONTSTR, FONT_SIZE2))
        radiobtn1.clicked.connect(lambda:self.radioClicked(radiobtn1))
        radiobtn2.clicked.connect(lambda:self.radioClicked(radiobtn2))
        self.radiobtn3.clicked.connect(lambda: self.radioClicked(self.radiobtn3))
        radiobtnhlayout = QHBoxLayout()
        radiobtnhlayout.addWidget(radiobtn1)
        radiobtnhlayout.addWidget(radiobtn2)
        radiobtnhlayout.addWidget(self.radiobtn3)
        radioWid = QWidget()
        radioWid.setLayout(radiobtnhlayout)
        self.layout.addWidget(radioWid)
        self.layout.addStretch()

    def radioClicked(self,sender):
        print(sender.text())
        if sender.text()== "Create Template":
            path = QFileDialog.getOpenFileName(self, 'Chose template image', '.', 'Image File (*.png *.jpg *.bmp *.jpeg *.tif *.ico)')[0]
            if path == None or path == '':
                return
            else:
                self.drawRect=drawRect(path)
                QMessageBox.information(self, u'success', 'Template was saved successfully')
        elif sender.text() == "Load Template":
            path = QFileDialog.getOpenFileName(self,'Chose template file(.shm)','.','File (*.shm)')[0]
            if path == None or path == '':
                return
            else:
                self.drawRect=drawRect(path)
                QMessageBox.information(self, u'success', 'Template Loaded successfully')
                self.radiobtn3.setEnabled(True)
        else:
            imgsDir = QFileDialog.getExistingDirectory(self,'Chose Images Directory','.')
            if imgsDir == None or imgsDir == '':
                return
            filelist = os.listdir(imgsDir)
            for name in filelist:
                if name.split('.')[-1] in ['jpg','png','bmp','jpeg','tif','ico']:
                    if self.drawRect.doublemodel != None:
                        self.drawRect.baizhengImage(os.path.join(imgsDir,name))
                    elif self.drawRect.model != None:
                        self.drawRect.getLabelAngle(os.path.join(imgsDir,name))
    def startImgZQ(self):
        print(self.imageZQList)
        if self.imageZQList !=[]:
            IP = imageProcessor(self.enhanceImgdir,self.enhanceImgdir)
            IP.imgeprocessorFun(self.imageZQList,IP.datas)
            self.imageZQList = []

    def getLabelNumbtn(self,name,btn1,btn2):
        btn1.clicked.connect(lambda: self.pLusNum(btn1))
        btn1.setObjectName('{}_p'.format(name))
        btn2.clicked.connect(lambda: self.minusNum(btn2))
        btn2.setObjectName('{}_m'.format(name))
        return btn1,btn2

    def pLusNum(self,btn):
        print('p',btn.objectName())
        if btn.objectName()== 'vertical_flip_p':
           self.imageZQList.append(0)
           num = int(self.labelNumDic['0'].text())+1
           self.labelNumDic['0'].setText(str(num))
        elif btn.objectName()== 'horizon_flip_p':
            self.imageZQList.append(1)
            num = int(self.labelNumDic['1'].text()) + 1
            self.labelNumDic['1'].setText(str(num))
        elif btn.objectName()== 'rotation_p':
            self.imageZQList.append(2)
            num = int(self.labelNumDic['2'].text()) + 1
            self.labelNumDic['2'].setText(str(num))
        elif btn.objectName()== 'translate_p':
            self.imageZQList.append(3)
            num = int(self.labelNumDic['3'].text()) + 1
            self.labelNumDic['3'].setText(str(num))
        elif btn.objectName()== 'deform_p':
            self.imageZQList.append(4)
            num = int(self.labelNumDic['4'].text()) + 1
            self.labelNumDic['4'].setText(str(num))
        elif btn.objectName()== 'scretch_p':
            self.imageZQList.append(5)
            num = int(self.labelNumDic['5'].text()) + 1
            self.labelNumDic['5'].setText(str(num))
        elif btn.objectName()== 'hue_p':
            self.imageZQList.append(6)
            num = int(self.labelNumDic['6'].text()) + 1
            self.labelNumDic['6'].setText(str(num))
        elif btn.objectName()== 'bright_p':
            self.imageZQList.append(7)
            num = int(self.labelNumDic['7'].text()) + 1
            self.labelNumDic['7'].setText(str(num))
        elif btn.objectName()== 'crop_p':
            self.imageZQList.append(8)
            num = int(self.labelNumDic['8'].text()) + 1
            self.labelNumDic['8'].setText(str(num))
        elif btn.objectName()== 'saturation_p':
            self.imageZQList.append(9)
            num = int(self.labelNumDic['9'].text()) + 1
            self.labelNumDic['9'].setText(str(num))

    def minusNum(self,btn):
        nulist = self.imageZQList[::-1]
        def delNum(m,list):
            for n in list:
                if n == m:
                    list.remove(n)
                    num = int(self.labelNumDic[str(m)].text()) - 1
                    self.labelNumDic[str(m)].setText(str(num))
                    self.imageZQList = list[::-1]
                    return
        if btn.objectName()=='vertical_flip_m':
           delNum(0,nulist)
        elif btn.objectName()== 'horizon_flip_m':
            delNum(1, nulist)
        elif btn.objectName()== 'rotation_m':
            delNum(2, nulist)
        elif btn.objectName()== 'translate_m':
            delNum(3, nulist)
        elif btn.objectName()== 'deform_m':
            delNum(4, nulist)
        elif btn.objectName()== 'scretch_m':
            delNum(5, nulist)
        elif btn.objectName()== 'hue_m':
            delNum(6, nulist)
        elif btn.objectName()== 'bright_m':
            delNum(7, nulist)
        elif btn.objectName()== 'crop_m':
            delNum(8, nulist)
        elif btn.objectName()== 'saturation_m':
            delNum(9, nulist)
        print(self.imageZQList)

    def createImgZQLabel(self,tittle):
        labelTittle = QLabel(tittle)
        labelTittle.setFont(QFont(FONTSTR,FONT_SIZE2))
        labelTittle.setFixedSize(80,20)
        labelNum = QLabel('0')
        labelNum.setFont(QFont(FONTSTR, FONT_SIZE2))
        labelNum.setAlignment(Qt.AlignCenter)
        labelNum.setObjectName(tittle)
        labelNum.setFixedSize(50,20)
        hboxlayout = QHBoxLayout()
        hboxlayout.addWidget(labelTittle,0)
        hboxlayout.addWidget(labelNum,1)
        btnlayout= QVBoxLayout()
        btnlayout.setSpacing(0)
        btnlayout.addStretch()
        btnPlus = QPushButton("+")
        btnPlus.setFont(QFont(FONTSTR, FONT_SIZE2))
        btnPlus.setFixedSize(20,20)
        btnMinus = QPushButton("-")
        btnMinus.setFont(QFont(FONTSTR, FONT_SIZE2))
        btnMinus.setFixedSize(20, 20)
        btnlayout.addStretch()
        btnlayout.addWidget(btnPlus)
        btnlayout.addWidget(btnMinus)
        btnlayout.addStretch()
        btnWid = QWidget()
        btnWid.setLayout(btnlayout)
        hboxlayout.addStretch()
        hboxlayout.addWidget(btnWid)
        widget = QWidget()
        widget.setLayout(hboxlayout)
        labelNum.setAutoFillBackground(True)
        widget.setAutoFillBackground(True)
        palette = QPalette()
        palette.setColor(QPalette.Window, Qt.lightGray)
        widget.setPalette(palette)
        widget.setFixedSize(200,70)

        return widget,btnPlus,btnMinus,labelNum




